﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WCBG.ToolsForUnity.Tools;

public class RaycastHolder : MonoBehaviour {


    public string timelineID;
    public string eventID;
    public bool isEnable;

    private Camera cam;

    // Use this for initialization
    void Start () {
        cam = GetComponent<Camera>();

        EventBus.Instance.AddEventHandler<string>(EventID.ON_TIMELINE_RAYCAST_ENABLE, OnRaycastEnable);
        EventBus.Instance.AddEventHandler<string>(EventID.ON_TIMELINE_RAYCAST_CLOSE, OnRaycastClose);

        FEasyInput.AddEvent(EEasyInputType.OnDown, OnDown);
        FEasyInput.AddEvent(EEasyInputType.OnUp, OnUp);
    }

    public void Initialize(string timelineID)
    {
        this.timelineID = timelineID;
    }

    private void OnRaycastEnable(string eventID)
    {
        if (!gameObject.activeSelf)
            return;
        isEnable = true;
        this.eventID = eventID;
    }
    private void OnRaycastClose(string eventID)
    {
        if (this.eventID == eventID)
        {
            isEnable = false;
        }
    }

    private void OnDestroy()
    {
        EventBus.Instance.RemoveEventHandler<string>(EventID.ON_TIMELINE_RAYCAST_ENABLE, OnRaycastEnable);
        EventBus.Instance.RemoveEventHandler<string>(EventID.ON_TIMELINE_RAYCAST_CLOSE, OnRaycastClose);

        FEasyInput.RemoveEvent(EEasyInputType.OnDown, OnDown);
        FEasyInput.RemoveEvent(EEasyInputType.OnUp, OnUp);
    }

    private void OnDown()
    {
        if (!isEnable)
            return;

        if (FTimelineDispatch.IsPlaying(timelineID))
            return;

        Transform target = FTools.GetRaycastHitTarget(cam, Input.mousePosition, 999999);
        BaseTrackHolder holder = target == null ? null : target.GetComponent<BaseTrackHolder>();
        if (holder != null)
        {
            holder.OnRaycast(eventID);
        }
    }

    private void OnUp()
    {

    }

}
